﻿using System;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using IServices;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Services.Dialogs;

namespace IntelligentParkingLot.ViewModels;

internal class LoginViewModel : BindableBase, IDialogAware
{
    private int _blurValue;
    private string _errorInfo;
    private bool _isRecord;

    private string _password = "";

    private string _userName;

    private readonly IUserService _userService;

    private bool _isShowLoading;

    public LoginViewModel(IUserService userService)
    {
        LoginCommand = new DelegateCommand(DoLogin);
        _userService = userService;

        // 读取登录记录
        if (!File.Exists("login.txt"))
        {
            IsRecord = false;
            return;
        }
        var info = File.ReadAllText("login.txt").Split('|');
        if (info.Length != 2)
            return;
        UserName = info[0];
        Password = info[1];
        IsRecord = true;
    }

    public int BlurValue
    {
        get => _blurValue;
        set => SetProperty(ref _blurValue, value);
    }

    public string ErrorInfo
    {
        get => _errorInfo;
        set => SetProperty(ref _errorInfo, value);
    }

    public bool IsRecord
    {
        get => _isRecord;
        set => SetProperty(ref _isRecord, value);
    }

    /// <summary>
    ///     是否显示加载动画
    /// </summary>
    public bool IsShowLoading
    {
        get => _isShowLoading;
        set => SetProperty(ref _isShowLoading, value);
    }

    public DelegateCommand LoginCommand { get; set; }

    public string Password
    {
        get => _password;
        set => SetProperty(ref _password, value);
    }

    public string UserName
    {
        get => _userName;
        set => SetProperty(ref _userName, value);
    }

    public event Action<IDialogResult> RequestClose;

    public string Title => "用户登录";

    public bool CanCloseDialog()
    {
        return true;
    }

    public void OnDialogClosed() { }

    public void OnDialogOpened(IDialogParameters dialogParameters) { }

    private void ShowLoading(bool state = true)
    {
        if (state)
        {
            IsShowLoading = true;
            BlurValue = 5;
        }
        else
        {
            IsShowLoading = false;
            BlurValue = 0;
        }
    }

    private void DoLogin()
    {
        ErrorInfo = "";
        ShowLoading();
        Task.Run(async () =>
        {
            await Task.Delay(1000);

            var result = _userService.Login(UserName, Password);

            if (null == result)
                ErrorInfo = "用户名或密码错误";

            Application.Current.Dispatcher.Invoke(() =>
            {
                // 关闭登录窗体，进去主界面
                RequestClose?.Invoke(new DialogResult(ButtonResult.OK));
            });
            if (IsRecord)
            {
                var info = $"{UserName}|{Password}";
                await File.WriteAllTextAsync("login.txt", info);
            }
            else
            {
                if (File.Exists("login.txt"))
                    File.Delete("login.txt");
            }

            ShowLoading(false);
        });
    }
}
